<?php
            
use app\model\Util; 
use app\model\Theme; 


/**
 * Author: cbw
 * Desc: 红包雨机会记录
 * Time: 2022/1/16 2:39 上午
 * Email: 17854288794@163.com
 */
class Chance_Page extends PluginWebPage {
    function main($method)
    {
        $method = 'chance_main';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;

        if (empty($_P['createtime']['start'])){
            $starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$starttime);
        }else{
            $start_day =  $_P['createtime']['start'];
            $starttime = strtotime($start_day);
        }
        $end_day = empty($_P['createtime']['end']) ? date('Y-m-d H:i:s',TIMESTAMP): $_P['createtime']['end'] ;
        $endtime = empty($_P['createtime']['end']) ? TIMESTAMP: strtotime($_P['createtime']['end']);


        $type = isset($_P['type'])?$_P['type']:'';
        $type_list = RedRainModel::getUserChanceTypeArr($themeid);

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $uid = isset($_P['uid'])?$_P['uid']:0;

        $lists = RedRainModel::searchUserRedRainChanceFlag($themeid,$type,$search_data,0,0,$start_day,$end_day,$uid);
        $list = RedRainModel::searchUserRedRainChanceFlag($themeid,$type,$search_data,$page_start,$page_size,$start_day,$end_day,$uid);

        $total = $page_total = count($lists);
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/redrain/chance/main', $return_clicent);
    }

    function nouse()
    {
        $method = 'no_used';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $page_total = RedRainModel::getNoUsedUserList($themeid,0,0,'',true);
        $total = intval($page_total);
        if(checksubmit('export_submit', true)){
            $page_limit = 2000;
            $pagesize = ceil($total/$page_limit);
            $header = array(
                'uid' => 'UID', 'nickname' => '昵称','username' => '姓名', 'mobile' => '手机', 'jihui' => '剩余抽奖次数',
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";

            $sql1 = "select uid from ".tablename(t_redrain_user_chance)." where chance >0 and themeid=$themeid group by uid";
            $res1 = db_select($sql1);
            $sql2 = "select uid from ".tablename(t_redrain_user_chance). " where chance =-1 and themeid=$themeid group by uid";
            $res2 = db_select($sql2);

            $add_arr = [];
            $used_arr = [];
            $diff_arr = [];
            foreach ($res1 as $key => $val) {
                if(!empty($val['uid'])){
                    array_push($add_arr, $val['uid']);
                }
            }
            foreach ($res2 as $k => $v) {
                if(!empty($v['uid'])){
                    array_push($used_arr, $v['uid']);
                }
            }
            $diff_arr = array_diff($add_arr,$used_arr);
//            for ($j = 1; $j <= $pagesize; $j++) {

                if (!$diff_arr){
                    $list = [];
                }else{
                    $diff_uid = '';
                    foreach ($diff_arr as $kk => $vv){
                        $diff_uid .= $vv.',';
                    }
                    $diff_uid = '('.rtrim($diff_uid,',').')';

                    $condition = "";
                    if ($search_data){
                        $condition .= " and a.nickname like '".$search_data."'"." or a.mobile like '".$search_data."' " ." or a.username like '".$search_data."' ";
                    }
                    $ex_page = $_P['ex_page']?$_P['ex_page']:1;
                    $condition .= " group by b.uid limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                    $sql = " select a.uid,a.nickname,a.avatar,a.username,a.mobile,a.jihui from ".tablename(t_fans)." as a ".
                        "left join ".tablename(t_redrain_user_chance)." as b on a.uid=b.uid and b.themeid=$themeid".
                        " where a.themeid=$themeid and a.uid in $diff_uid ".$condition;
                    $list =  db_select($sql);
                }
                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            if ($row['nickname']!='新用户' && $row['nickname']!='微信用户'){
                                $row['nickname'] = str_replace(',','',$row['nickname']);
                                $row['nickname'] = str_replace('"','',$row['nickname']);
                            }

                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
 //               }
            }
            //新版本导出合并
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            Util::WxJump($_S,$html,'未使用红包雨机会记录',$themeid,$is_end,$pagesize);
        }

        $list = RedRainModel::getNoUsedUserList($themeid,$page_start,$page_size,$search_data);
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/redrain/chance/nouse', $return_clicent);
    }

    //机会数据
    function userdata(){
        $method = 'chance_data';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 20;
        $page_start = ($page_index-1)*$page_size;

        $where = "  c.themeid=$themeid";
        //时间搜索
         if (empty($_P['createtime']['start'])){
             $starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
             $start_day =  date('Y-m-d H:i:s',$starttime);
         }else{
             $start_day =  $_P['createtime']['start'];
             $starttime = strtotime($start_day);
         }
         $end_day = empty($_P['createtime']['end']) ? date('Y-m-d H:i:s',TIMESTAMP): $_P['createtime']['end'] ;
         $endtime = empty($_P['createtime']['end']) ? TIMESTAMP: strtotime($_P['createtime']['end']);

        if ($start_day && $end_day) {
            $where .= "  and c.created_at between '" . $start_day . "' and '" . $end_day . "'";
        }
        //名称搜索
        $search = '';
         $search_data = isset($_P['search_data'])?$_P['search_data']:'';
         if ($search_data){
             $search = '%'.$search_data.'%';
         }
        if ($search) {
            $where .= " AND (f.nickname LIKE '" . $search . "'" . " or f.mobile LIKE '" . $search . "' " . " or f.username LIKE '" . $search . "' )";
        }
        //查询总记录数
        $total_sql = "select  count(DISTINCT c.uid)  as cnt,
                       sum(case when chance>0 then chance else 0 end)  all_chanece,
                       sum(case when chance<0 then 1 else 0 end)  all_used_chance,
                       sum(case when remaining_chance>0 then remaining_chance else 0 end)  all_remaining_chance 
                       from ".tablename(t_redrain_user_chance)." as c 
                       left join ".tablename(t_fans) ." as f on c.uid = f.uid and c.themeid = f.themeid
                       where ".$where;

        $total_data = db_find($total_sql);
        $total = $total_data['cnt'];

        if(checksubmit('export_submit', true)){
            $ex_page_size = 2000;
            $ex_page_index = max(1,intval($_P['ex_page']));
            $pagesize = ceil($total/$ex_page_size);
            $ex_page_start = ($ex_page_index-1)*$ex_page_size;
            $condition = " LIMIT " . $ex_page_start . "," . $ex_page_size;
        }else{
            $condition = " LIMIT " . $page_start . "," . $page_size;
        }

         $sql =   "select c.themeid,c.uid,f.uid,f.nickname,f.avatar,f.username,f.mobile,
                      sum(case when chance>0 then chance else 0 end)  all_chanece,
                      sum(case when chance<0 then 1 else 0 end)  all_used_chance,
                      sum(case when remaining_chance>0 then remaining_chance else 0 end)  all_remaining_chance  from ".tablename(t_redrain_user_chance)." as c 
                       left join ".tablename(t_fans) ." as f on c.uid = f.uid and c.themeid = f.themeid
                       where $where group by c.uid 
                       order by sum(case when chance>0 then chance else 0 end) desc,c.uid desc ".$condition;
         //and 'all_chanece' > 10

         $list = db_select($sql);
         //导出数据
         if(checksubmit('export_submit', true)){
             $header = array(
                 'uid' => 'UID',
                 'nickname' => '昵称',
                 'username' => '姓名',
                 'mobile' => '电话',
                 'all_chanece' => '总机会',
                 'all_used_chance' => '已使用',
                 'all_remaining_chance' => '未使用',
             );
             $keys = array_keys($header);
             $html = "\xEF\xBB\xBF";
             foreach ($header as $li) {
                 $html .= $li . "\t ,";
             }
             $html .= "\n";
             foreach ($list as $row) {
                 $row['nickname'] = str_replace(',','',$row['nickname']);  //字符串替换
                 $row['nickname'] = str_replace('"','',$row['nickname']);  //字符串替换
                 foreach ($keys as $key) {
                     $data[] = $row[$key];
                 }
                 if (isset($data)){
                     $user[] = implode("\t ,", $data) . "\t ,";
                     unset($data);
                 }
             }
             $html .= implode("\n", $user);
             //新版本导出合并

             $is_end = 0;
             if($ex_page_index==$pagesize){
                 $is_end = 1;
             }
             Util::WxJump($_S,$html,'机会记录',$themeid,$is_end,$pagesize);
         }
        $pager = pagination($total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/redrain/chance/userdata', $return_clicent);
    }


}